<?php

namespace Simanx\Spes\Attribute\Route\Permission;

use Simanx\Spes\Attribute\ClassAttributeProxy;
use Simanx\Spes\Attribute\Route\Permission\Attributes\Can;
use Simanx\Spes\Loader\Loader;

class PermissionLoader extends Loader
{
    public function load()
    {
        /** @var PermissionManager $permissionManager */
        $permissionManager = $this->app->make(PermissionManager::class);
        foreach ($this->classes() as $class) {
            $permissionClassAttribute = ClassAttributeProxy::create($class);
            /** @var Can $canAttribute */
            $canAttribute = $permissionClassAttribute->getAttribute(Can::class);
            if (!$canAttribute) {
                continue;
            }

            $permissionGroup = new PermissionGroup($canAttribute->permission, $canAttribute->name, $canAttribute->options);
            $methodCanAttributes = $permissionClassAttribute->getMethodAttributes(Can::class);
            /** @var Can $attribute */
            foreach ($methodCanAttributes as $attributes) {
                $attribute = $attributes[0] ?? null;
                if (!$attribute) {
                    continue;
                }

                $permission = new Permission(sprintf('%s.%s', $permissionGroup->permission, $attribute->permission), $attribute->name, $attribute->options);
                $permissionGroup->addChild($permission);
            }

            $permissionManager->add($permissionGroup);
        }
    }
}